// 引入React及相关Hooks
import React, { useCallback, useEffect, useRef, useState } from 'react';
// 引入React Native的基础组件和API
import { View, Text, TouchableOpacity, StyleSheet, Alert, Dimensions } from 'react-native';
// 引入React Navigation的hook，用于页面跳转
import { useNavigation } from '@react-navigation/native';
// 引入react-native-vision-camera的组件和类型
import { Camera, CameraPermissionStatus, CameraDevice, CameraRuntimeError, useCameraDevices } from 'react-native-vision-camera';
// 引入文件系统库，用于读取图片为base64
import RNFS from 'react-native-fs';
// 引入人脸登录API方法
import { faceLogin } from '../../ulits/instance';
// 引入Adapt utilities
import Adapt, {
  adapt,
  adaptFontSize,
  getScreenWidth,
  getScreenHeight,
  getStatusBarHeight,
} from '../../ulits/Adapt';

// 获取屏幕宽高，用于布局
const SCREEN_WIDTH = getScreenWidth();
const SCREEN_HEIGHT = getScreenHeight();
const STATUS_BAR_HEIGHT = getStatusBarHeight();

// 定义FaceRecognition组件
export default function FaceRecognition() {
  // 获取导航对象
  const navigation = useNavigation();
  // 创建camera组件的ref
  const camera = useRef<Camera>(null);
  // 摄像头权限状态
  const [hasPermission, setHasPermission] = useState(false);
  // 摄像头是否初始化完成
  const [isCameraReady, setIsCameraReady] = useState(false);
  // 是否正在识别中（防止重复操作）
  const [isRecognizing, setIsRecognizing] = useState(false);
  // 获取所有摄像头设备
  const devices = useCameraDevices();
  // 取前置摄像头
  const frontCamera = devices.find(device => device.position === 'front');

  // 检查并请求摄像头权限
  const checkPermission = useCallback(async () => {
    const permission = await Camera.getCameraPermissionStatus(); // 获取当前权限状态
    console.log('Initial permission:', permission);

    if (permission === 'not-determined') { // 如果未决定，弹出请求权限
      const newPermission = await Camera.requestCameraPermission();
      console.log('New permission:', newPermission);
      setHasPermission(newPermission === 'granted'); // 设置权限状态
    } else if (permission === 'denied') {
      // 如果权限被拒绝，直接返回上一页
      navigation.goBack();
    } else {
      setHasPermission(permission === 'granted'); // 已有权限则直接赋值
    }
  }, [navigation]);

  // 组件挂载后检查权限，只在组件首次加载时执行一次
  useEffect(() => {
    checkPermission();
  }, []); // 空依赖数组，确保只执行一次

  // 摄像头初始化回调
  const onCameraReady = useCallback(() => {
    console.log('Camera is ready');
    setIsCameraReady(true);
  }, []);

  // 摄像头错误回调
  const onError = useCallback((error: CameraRuntimeError) => {
    console.error('Camera error:', error);
    Alert.alert('错误', '摄像头初始化失败，请重试');
  }, []);

  // 文件路径转base64
  const convertToBase64 = async (path: string): Promise<string> => {
    try {
      console.log('Reading file from path:', path);
      const fileContent = await RNFS.readFile(path, 'base64'); // 读取文件
      console.log('File read successfully, base64 length:', fileContent.length);
      return fileContent;
    } catch (error) {
      console.error('Error converting to base64:', error);
      throw new Error('转换图片格式失败');
    }
  };

  // 处理拍照和识别流程
  const handleCapture = useCallback(async () => {
    if (!camera.current || !isCameraReady || isRecognizing || !frontCamera) {
      // 拍照条件未满足则返回
      console.log('Cannot take photo:', {
        hasCamera: !!camera.current,
        isCameraReady,
        isRecognizing,
        hasFrontCamera: !!frontCamera
      });
      return;
    }

    setIsRecognizing(true); // 标记正在识别
    try {
      // 1. 拍照
      console.log('Taking photo...');
      const photo = await camera.current.takePhoto({
        flash: 'off',
      });
      console.log('Photo captured:', photo);

      // 2. 转base64
      const base64Data = await convertToBase64(photo.path);
      console.log('Base64 conversion completed, length:', base64Data.length);

      // 3. 调用后端人脸识别API
      console.log('Calling face recognition API...');
      const result = await faceLogin(base64Data);
      console.log('Face recognition result:', result);

      // 4. 处理识别结果
      if (result.code === 0 && result.data) {
        const { PersonName } = result.data;
        Alert.alert(
          '登录成功',
          `欢迎回来，${PersonName}`,
          [
            {
              text: '确定',
              onPress: () => {
                // 登录成功后的跳转
                navigation.navigate('MeTab' as never);
              }
            }
          ]
        );
      } else {
        // 识别失败，提示用户并询问是否前往注册
        Alert.alert(
          '识别失败',
          '未找到匹配的人员信息，是否前往录入？',
          [
            {
              text: '取消',
              style: 'cancel'
            },
            {
              text: '去录入',
              onPress: () => {
                navigation.navigate('FaceLR' as never);
              }
            }
          ]
        );
      }
    } catch (error) {
      console.error('Recognition error:', error);
      // 发生错误时也提供录入选项
      Alert.alert(
        '识别出错',
        '是否前往人员录入？',
        [
          {
            text: '取消',
            style: 'cancel'
          },
          {
            text: '去录入',
            onPress: () => {
              navigation.navigate('FaceRegistration' as never);
            }
          }
        ]
      );
    } finally {
      setIsRecognizing(false); // 恢复识别按钮
    }
  }, [isCameraReady, isRecognizing, frontCamera, navigation]);

  // 若无权限，则显示简单的提示并返回
  if (!hasPermission) {
    return (
      <View style={styles.container}>
        <View style={styles.messageContainer}>
          <Text style={styles.title}>需要相机权限</Text>
          <TouchableOpacity
            style={styles.primaryBtn}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.btnText}>返回</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  // 若前置摄像头未初始化
  if (!frontCamera) {
    return (
      <View style={styles.container}>
        <View style={styles.messageContainer}>
          <Text style={styles.title}>正在初始化</Text>
          <Text style={styles.subtitle}>正在准备摄像头...</Text>
        </View>
      </View>
    );
  }

  // 正常渲染摄像头和UI
  return (

    <View style={styles.container}>
      {/* 摄像头画面区域，做了垂直镜像 */}
      <View style={styles.cameraWrapper}>
        <Camera
          ref={camera}
          style={styles.camera}
          device={frontCamera}
          isActive={true}
          photo={true}
          onError={onError}
          onInitialized={onCameraReady}
        />
      </View>

      {/* UI叠加层 */}
      <View style={styles.overlay}>
        {/* 顶部提示 */}
        <View style={[styles.header, { marginTop: STATUS_BAR_HEIGHT + adapt(16) }]}>
          <Text style={styles.title}>人脸识别登录</Text>
          <Text style={styles.subtitle}>请将面部置于圆形框内</Text>
        </View>

        {/* 人脸引导圆环 */}
        <View style={styles.guideContainer}>
          <View style={styles.faceGuideRing} />
        </View>

        {/* 底部按钮 */}
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[styles.captureBtn, !isCameraReady && styles.disabledBtn]}
            onPress={handleCapture}
            disabled={!isCameraReady || isRecognizing}
          >
            <Text style={styles.btnText}>
              {isRecognizing ? '识别中...' : '开始识别'}
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.cancelBtn}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.btnText}>返回</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}

// 样式表
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000', // 全黑背景
  },
  cameraWrapper: {
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    transform: [{ scaleY: -1 }], // 垂直翻转，适配前置镜像
  },
  camera: {
    width: '100%',
    height: '100%',
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.5)', // 半透明黑色遮罩
  },
  messageContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: adapt(20),
  },
  header: {
    alignItems: 'center',
  },
  title: {
    fontSize: adaptFontSize(24),
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: adapt(8),
  },
  subtitle: {
    fontSize: adaptFontSize(16),
    color: '#fff',
    opacity: 0.8,
  },
  guideContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  faceGuideRing: {
    width: adapt(250),
    height: adapt(250),
    borderRadius: adapt(125),
    borderWidth: Adapt.DeviceType.isIOS ? 2 : 3,
    borderColor: '#FFD700',
    borderStyle: 'dashed',
  },
  buttonContainer: {
    alignItems: 'center',
    paddingBottom: adapt(50),
  },
  captureBtn: {
    backgroundColor: '#FF9500',
    paddingHorizontal: adapt(60),
    paddingVertical: adapt(15),
    borderRadius: adapt(25),
    marginBottom: adapt(15),
  },
  cancelBtn: {
    backgroundColor: 'rgba(255,255,255,0.3)',
    paddingHorizontal: adapt(60),
    paddingVertical: adapt(15),
    borderRadius: adapt(25),
  },
  btnText: {
    color: '#fff',
    fontSize: adaptFontSize(18),
    fontWeight: '600',
  },
  disabledBtn: {
    opacity: 0.5,
  },
  primaryBtn: {
    backgroundColor: '#FF9500',
    paddingHorizontal: adapt(40),
    paddingVertical: adapt(12),
    borderRadius: adapt(20),
    marginTop: adapt(20),
  },
});